package com.fingard.dsp.bank.directbank.egbank01;


import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.net.*;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import sun.misc.BASE64Encoder;

import javax.net.ssl.*;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;

public class EGBANK01Base extends DirectBase implements ITcpClient {

    protected static final String INSERTSEQ = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";
    protected static final String SELECTSEQ = "SELECT TRANSDATE,BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=? AND BANKCODE=?;";

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    protected static String  boundary ="--------------------HV2ymHFg03ehbqgZCaKO6jyH";
    protected static String end = "\r\n";


    private String getSignCharset() {
        return getBankConfig().getCharset("GBK", "sign");
    }

    private static TransIDHelper idHelper = new TransIDHelper(1, 999);
    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    private String getBnkToken() {

        boolean isLoginValid = true;
        if (StringHelper.isNullOrEmpty(bankFront.token)) {
            isLoginValid = false;
        } else if (bankFront.lastVisitTime == null) {
            isLoginValid = false;
        } else {
            int timeOut = getBankConfig().getValueAsInt("sessionTimeOut");
            timeOut = timeOut <= 0 ? 10 : timeOut;
            Date currDate = new Date();
            if (DateHelper.getDifferMins(currDate, bankFront.lastVisitTime) > timeOut) {
                isLoginValid = false;
            } else if (DateHelper.compareDay(currDate, bankFront.lastVisitTime) != 0) {
                isLoginValid = false;
            }
        }

        if (!isLoginValid) {
            WriteBankLogLn("当前未登录前置或已登录超时，现在进行登录");
            login();

        }
        return bankFront.token;
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter, EGBANK01Header p_bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.opName)) {
            throw new Exception("未赋值opName");
        }
        if (StringHelper.isNullOrEmpty(p_bankHeader.serialNo)) {
            throw new Exception("未赋值serialNo");
        }
        xmlWriter.writeStartDocument();
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("HFBankData");
        if(!p_bankHeader.opName.equals("uploadFileSalary") || !p_bankHeader.opName.equals("querySalaryDetailResultOp")) {
            xmlWriter.writeStartElement("sign");
            xmlWriter.writeElementString("signedData", "1");
            xmlWriter.writeEndElement();
        }
        xmlWriter.writeStartElement("opReq");
        xmlWriter.writeElementString("serialNo", p_bankHeader.serialNo);//地区
        if (p_bankHeader.reqTime == null) {
            p_bankHeader.reqTime = new Date();
        }
        if(p_bankHeader.opName.equals("querySalaryDetailResultOp")||p_bankHeader.opName.equals("querySalarySummaryOp")){
            xmlWriter.writeElementString("cstNo", bankFront.loginName);
        }
        if(p_bankHeader.opName.equals("uploadFileSalary") || p_bankHeader.opName.equals("submitGZBatchOp")){
            xmlWriter.writeElementString("cstNo", bankFront.loginName);
        }
        xmlWriter.writeElementString("reqTime", Format.DateTime14Format.format(p_bankHeader.reqTime));
        if(!p_bankHeader.opName.equals("submitGZBatchOp")) {
            xmlWriter.writeElementString("erpPid", bankFront.operator);
        }
    }
    //密码加密,先sha1,然后base64,即base64(sha1("pass"))
    private static String encodePassword(String pass) throws Exception {
        String encPass = pass;
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        byte[] sha1Passbytes = sha1.digest(encPass.getBytes());
        String base64Sha1Passstr = "";
        if (sha1Passbytes != null) {
            base64Sha1Passstr = new BASE64Encoder().encode(sha1Passbytes);
        }
        return base64Sha1Passstr;
    }

    protected void login() {
        try {
            int tmpMaxFailCount = getBankConfig().getValueAsInt("maxLoginFail");
            if (bankFront.loginFailCount >= tmpMaxFailCount) {
                WriteBankLogLn("登录失败次数" + bankFront.loginFailCount + "已达到上限，不再进行登录");
                return;
            }
            bankFront.lastLoginTime = new Date();
            bankFront.token = "";

            EGBANK01Header tmpHeader = new EGBANK01Header();
            tmpHeader.opName = "CebankUserLogonOp";
            tmpHeader.serialNo = getQryTransID();
            tmpHeader.needSigned = true;
            tmpHeader.signStrList = new String[]{"serialNo", "reqTime", "erpPid", "cstNo", "userPWD"};

            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, tmpHeader);
            xmlWriter.writeStartElement("reqParam");
            xmlWriter.writeElementString("cstNo", bankFront.loginName);
            if(this.getBankConfig().getValueAsBool("useEncrypPassWord")){
                xmlWriter.writeElementString("userPWD", bankFront.loginPasswd);
            }else {
                xmlWriter.writeElementString("userPWD", encodePassword(bankFront.loginPasswd));
            }
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBankLogin(xmlWriter.toXmlString(), tmpHeader);
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();

                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/HFBankData/opRep/retCode");
                    String tmprspmsg = tmpBkReader.getFirstText("/HFBankData/opRep/errMsg");
                    if (tmprspcod.equals("0")) {
                        bankFront.token = tmpBkReader.getFirstText("/HFBankData/opRep/opResult/sessionID");
                        bankFront.loginFailCount = 0;
                        WriteBankLogLn("登录成功");
                    } else {
                        bankFront.loginFailCount = bankFront.loginFailCount + 1;
                        WriteBankLogLn("登录失败：" + tmprspmsg);
                    }
                } else {
                    WriteBankLogLn("登录失败");
                }
            } else {
                WriteBankLogLn("登录失败：" + tmpStrRet[1]);
            }
        } catch (Exception e) {
            WriteBankLogLn("登录异常：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private String generateSignPlain(String p_original, EGBANK01Header p_bankHeader) throws Exception {
        WriteBankLogLn2("需生成签名格式报文的原文为：" + p_original);
        XmlTextReader xmlTextReader = new XmlTextReader(p_original);
        StringBuilder tmpSb = new StringBuilder();
        for (String field : p_bankHeader.signStrList) {
            tmpSb.append(String.format("#$%s=%s", field, xmlTextReader.getSimpleTextNotNull(field)));
            WriteBankLogLn2("签名字段为：" + field + "：" + xmlTextReader.getSimpleTextNotNull(field));
        }

        String signPlainText = tmpSb.toString();
        int length = signPlainText.getBytes("GB2312").length; //signReq.Length;
        signPlainText = "POST /servlet/ABC95599.Trans HTTP/1.1" + "\r\n" +
                "Content-Type: INFOSEC_SIGN/1.0" + "\r\n" +
                "Content-Length: " + length + "\r\n" +
                "User-Agent: Jakarta Commons-HttpClient/2.0.2" + "\r\n" +
                "Host: 127.0.0.1" + "\r\n" +
                "\r\n" + signPlainText;
        return signPlainText;
    }

    private boolean getSignedData(String p_reqStr,EGBANK01Header p_bankHeader, StringBuilder p_sb) {
        try {
            String p_signPlain = generateSignPlain(p_reqStr,p_bankHeader);
            WriteBankLogLn("提交银行进行签名的报文为：" + p_signPlain);
            TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.signPort), this);
            WriteBankLogLn("提交银行进行签名的地址为：" + bankFront.serverIP + ":" + bankFront.signPort);
            TcpReceiver tmpReceiver = tmpClient.sendMessage(p_signPlain.getBytes(getSignCharset()));
            if (tmpReceiver.connState.equals(ConnState.FAIL)) {
                p_sb.append("签名通讯失败，请排查！");
                return false;
            }
            String retXmlStr = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, getSignCharset());
            WriteBankLogLn("签名返回报文：" + retXmlStr);
            if (!(retXmlStr.startsWith("HTTP/1.0 200 OK") && retXmlStr.contains("<html>"))) {
                p_sb.append(String.format("签名失败，返回签名结果：", retXmlStr));
                return false;
            }
            retXmlStr = retXmlStr.substring(retXmlStr.indexOf("<html>"));
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retXmlStr, p_sb);
            if (tmpBkReader != null) {
                String result = tmpBkReader.getFirstText("/html/head/result");
                if (result.equals("0")) {
                    p_sb.append(tmpBkReader.getFirstText("/html/body/sign"));
                    return true;
                } else {
                    p_sb.append(String.format("签名失败，返回签名结果：", retXmlStr));
                    return false;
                }
            } else {
                return false;
            }

        } catch (Exception ex) {
            p_sb.append(ex.getMessage());
            return false;
        }
    }

    protected String getSessionID(EGBANK01Header bankHeader){


        String sessionID = getBnkToken();
        if (StringHelper.isNullOrEmpty(sessionID)) {
            return null;
        }
        bankFront.lastVisitTime = new Date();
        return sessionID;
    }

    /**
     * 文件上传
     * @return
     */
    protected String[] uploadFileToBank(String data, String path, EGBANK01Header bankHeader, ReqBatPayRec payRec) {
        String[] retStr = new String[]{"", ""};
        WriteBankLogLn("发送给银行的上传请求报文：" + data);
        try {
            StringBuilder sb = new StringBuilder();
            if (bankHeader.needSigned) {
                boolean isSignedSuccess = getSignedData(data,bankHeader, sb);
                if (isSignedSuccess) {
                    data = data.replace("<signedData>1</signedData>", String.format("<signedData>%s</signedData>", sb.toString()));
                } else {
                    retStr[0] = ConnState.FAIL;
                    retStr[1] = sb.toString();
                    return retStr;
                }
            }
            String sessionID = getBnkToken();

            bankFront.lastVisitTime = new Date();

            String serverUrl = String.format("%s/HFYQService/uploadFileSalary?dse_sessionId=%s", bankFront.getUrl("upload"), bankFront.token);
            String name=path.substring(path.lastIndexOf("\\")+1,path.length());
            File file = new File(path);
            trustAllHttpsCertificates();
            CloseableHttpClient client = getHttpsClient();

            HttpPost httpPost = new HttpPost(serverUrl);
            //添加标准表单形式 application/x-www-form-urlencoded
            //     Header header = new BasicHeader("Content-type","application/x-www-form-urlencoded"); //此处不需要再额外添加头部信息，会自动添加好的
            //处理文件 后面的setMode是用来解决文件名称乱码的问题:以浏览器兼容模式运行，防止文件名乱码。
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setCharset(Charset.forName("UTF-8")).addBinaryBody("uploadFile", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, name);
            //     httpPost.setHeader(header);
            builder.addTextBody("sessionID", sessionID);
            builder.addTextBody("sessionId", sessionID);
            builder.addTextBody("serialNo", bankHeader.serialNo);
            builder.addTextBody("cstNo", bankFront.loginName);
            builder.addTextBody("reqTime", Format.DateTime14Format.format(bankHeader.reqTime));
       //     builder.addTextBody("uploadFile", name);
            builder.addTextBody("payAccount", payRec.ownAct);
            builder.addTextBody("totalAmount", payRec.totalAmt);
            builder.addTextBody("totalNumber", payRec.totalNum);
            builder.addTextBody("reqData", data);
            HttpEntity httpEntity = builder.build();
            httpPost.setEntity(httpEntity);
            HttpResponse httpResponse = client.execute(httpPost);
            HttpEntity responseEntity = httpResponse.getEntity();
            retStr[1] = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            WriteBankLogLn("上传工资发送消息收到的返回：" + retStr[1]);

            if (retStr[0].length() == 0 && retStr[1].contains("Session not established or timeout!")) {
                bankFront.token = "";
            }

        } catch (MalformedURLException e) {
            WriteBankLogLn("与银行通讯失败,上传文件失败：" + e.getMessage());
        } catch (Exception e) {
            WriteBankLogLn("与银行通讯失败,上传文件失败：" + e.getMessage());
        }
        WriteBankLogLn("上传文件结果返回报文：" + retStr[1]);

        return retStr;
    }

    /*
    protected void ConfigHttpMultipart(final OutputStream out,String filepath,String data,String sessionID) throws Exception{
        byte[] tmpToWriteBytes = data.getBytes("UTF-8");

        MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
        mEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        mEntityBuilder.addBinaryBody("file", new File(filepath));
        String name=filepath.substring(filepath.lastIndexOf("\\")+1,filepath.length());
        StringBuffer params = new StringBuffer();
        params.append(boundary + newLine);
        params.append("Content-Disposition: form-data;name=\"sessionId\"").append(sessionID).append("\"");
        params.append(boundary + newLine);
        params.append("Content-Disposition: form-data;name=\"sessionID\"").append(sessionID).append("\"");
        params.append(boundary + newLine);
        params.append("Content-Disposition: form-data; name=\"uploadFile\"; filename=\"").append(name).append("\"")
        .append(newLine).append("Content-Type:application/octet-stream");
        params.append(newLine);
        File file = new File(filepath);
        try {
            out.write(params.toString().getBytes("UTF-8"));
            DataInputStream dis = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[(int) file.length()];
            bytes = dis.read(bufferOut);
            out.write(bufferOut,0,bytes);
            dis.close();
  //          out.write(readBuffer(in));
            out.write(newLine.getBytes("UTF-8"));
            out.write((boundary + newLine).getBytes("UTF-8"));
            out.write(tmpToWriteBytes);
            String  endboundary = "\r\n--"+boundary+"--\r\n";
            out.write(endboundary.getBytes("UTF-8"));
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            out.close();
        }
    }*/

    public static byte[] readBuffer(final InputStream ins) throws IOException {
        byte b[] = new byte[1024];
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        int len = 0;
        while ((len = ins.read(b)) != -1) {
            stream.write(b, 0, len);
        }
        return stream.toByteArray();
    }

    protected String[] sendToBank(String p_reqStr, EGBANK01Header p_bankHeader) throws Exception {
        String tmpSendContent = p_reqStr;
        String[] retStr = new String[]{"", ""};
        StringBuilder sb = new StringBuilder();
        if (p_bankHeader.needSigned) {
            boolean isSignedSuccess = getSignedData(p_reqStr,p_bankHeader, sb);
            if (isSignedSuccess) {
                tmpSendContent = tmpSendContent.replace("<signedData>1</signedData>", String.format("<signedData>%s</signedData>", sb.toString()));
            } else {
                retStr[0] = ConnState.FAIL;
                retStr[1] = sb.toString();
                return retStr;
            }
        }

        String sessionID = getBnkToken();
        if (StringHelper.isNullOrEmpty(sessionID)) {
            retStr[0] = ConnState.FAIL;
            retStr[1] = "自动登录失败，需先登录！";
            return retStr;
        }

        bankFront.lastVisitTime = new Date();
        String url = "";

            url = String.format("%s/HFYQService/APIReqServlet?dse_sessionId=%s&opName=%s", bankFront.serverURL, bankFront.token, p_bankHeader.opName);
            WriteBankLogLn("提交银行的地址：" + url);
            WriteBankLogStep2(tmpSendContent);
            byte[] tmpToWriteBytes = tmpSendContent.getBytes(getCharset());
            WebRequest tmpWebRequest = new WebRequest(url);
            tmpWebRequest.setConnectTimeout(60000);
            tmpWebRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            tmpWebRequest.setRequestProperty("connection", "Close");
            retStr = tmpWebRequest.upload(tmpToWriteBytes, getCharset());
            if (retStr[0].length() == 0 && retStr[1].contains("Session not established or timeout!")) {
                bankFront.token = "";
            }
            WriteBankLogStep3(retStr[1]);
            return retStr;
    }

    protected String[] sendToBankLogin(String p_reqStr, EGBANK01Header p_bankHeader) throws Exception {
        String tmpSendContent = p_reqStr;
        String[] retStr = new String[]{"", ""};
        StringBuilder sb = new StringBuilder();
        if (p_bankHeader.needSigned) {
            boolean isSignedSuccess = getSignedData(p_reqStr, p_bankHeader, sb);
            WriteBankLogLn("签名返回结果：" + sb.toString());
            if (isSignedSuccess) {
                tmpSendContent = tmpSendContent.replace("<signedData>1</signedData>", String.format("<signedData>%s</signedData>", sb.toString()));
            } else {
                retStr[0] = ConnState.FAIL;
                retStr[1] = sb.toString();
                return retStr;
            }
        }
        bankFront.lastVisitTime = new Date();
        String url = String.format("%s/HFYQService/APISessionReqServlet?opName=%s", bankFront.serverURL, p_bankHeader.opName);
        WriteBankLogLn("提交银行的地址：" + url);
        WriteBankLogStep2(tmpSendContent);
        byte[] tmpToWriteBytes = tmpSendContent.getBytes(getCharset());
        WebRequest tmpWebRequest = new WebRequest(url);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        tmpWebRequest.setRequestProperty("connection", "Close");
        retStr = tmpWebRequest.upload(tmpToWriteBytes, getCharset());
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = getCharset();
            String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
            if (tmpRecNow.contains("</html>")) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }
    /**
     * Excel解析读取
     *
     * @param filepath
     * @return
     * @throws Exception
     */
    public String readExcel(String filepath) throws Exception {
        try {
            Workbook wb = new HSSFWorkbook(new FileInputStream(filepath));
            Sheet sheet = wb.getSheetAt(0);

            StringBuilder sbFileContent = new StringBuilder();
            for (int i = 2; i < sheet.getLastRowNum(); i++) {
                Row detailRow = sheet.getRow(i);
                if (detailRow == null) {// 略过空行
                    continue;
                }
                if (sbFileContent.length() > 0) {
                    sbFileContent.append("\r\n");
                }
                int cellSize = detailRow.getLastCellNum();
                StringBuilder eachline = new StringBuilder();
                for (int k = 0; k < cellSize; k++) {
                    Cell cell = detailRow.getCell(k);
                    if (eachline.length() > 0) {
                        eachline.append(",");
                    }
                    eachline.append(getCellValue(cell));
                }
                sbFileContent.append(eachline);
            }
            return sbFileContent.toString();
        } catch (FileNotFoundException e) {
            return "";
        }
    }
    /**
     * 获取Excel某列的值
     *
     * @param cell
     * @return
     */
    public static String getCellValue(Cell cell){
        String cellValue = "";
        if(cell == null){
            return cellValue;
        }

        //把数字当成String来读，避免出现1读成1.0的情况
        if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
            if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                Date theDate = cell.getDateCellValue();
                SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                cellValue = dff.format(theDate);
            }else{
                cell.setCellType(Cell.CELL_TYPE_STRING);
            }
        }

        //判断数据的类型
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC: //数字
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    Date theDate = cell.getDateCellValue();
                    SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    cellValue = dff.format(theDate);
                }else{
                    cellValue = String.valueOf(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }

    /**
     * 批量汇款提交文件，返回文件路径
     * @param dse_sessionid 请求时的sessionid
     * @param  待汇款列表，为了生成文件提供内容
     * @param fileName 文件名称，可选
     * @return
     * @throws Exception <retCode>YQ0800061</retCode><errMsg>上传文件失败</errMsg>

    private String uploadFile(String dse_sessionid,String filePath,String baowen,String fileName,String responsorUrl ) throws Exception {
        //需要使用支持文件的entity
        System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
     //   MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,"--------------------HV2ymHFg03ehbqgZCaKO6jyH", Charset.forName("UTF-8"));
     //   multipartEntity.addPart("sessionId",new StringBody(dse_sessionid,Charset.forName("UTF-8")));
     //   multipartEntity.addPart("reqData",new StringBody(baowen,Charset.forName("UTF-8")));

        //关键的一步，把文件参数压入请求
     //   multipartEntity.addPart("uploadFile",new FileBody(new File(filePath), ContentType.create("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "UTF-8"),fileName));
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(responsorUrl);
    //    HttpPost request = new HttpPost(responsorUrl);
  //      postMethod.setRequestEntity(multipartEntity);
        String name=filePath.substring(filePath.lastIndexOf("\\")+1,filePath.length());

        FilePart filePart = new FilePart("file",name,new File(filePath));
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(new Part[]{new StringPart("HIDDEN","from",baowen),filePart},postMethod.getParams());
        postMethod.addParameter(new NameValuePair("sessionId",dse_sessionid));
        postMethod.addParameter(new NameValuePair("reqData",dse_sessionid));
        postMethod.addParameter(new NameValuePair("sessionId",dse_sessionid));
        postMethod.addParameter(new NameValuePair("sessionId",dse_sessionid));
        postMethod.addParameter(new NameValuePair("sessionId",dse_sessionid));
        postMethod.addParameter(new NameValuePair("sessionId",dse_sessionid));
        postMethod.addParameter(new NameValuePair("sessionId",dse_sessionid));
        postMethod.addParameter(new NameValuePair("sessionId",dse_sessionid));
        postMethod.setRequestEntity(multipartRequestEntity);

        httpClient.getParams().setContentCharset("UTF-8");
     //   request.addHeader("Content-Type","multipart/form-data; boundary=--------------------HV2ymHFg03ehbqgZCaKO6jyH");
    //    request.addHeader("User-Agent", "AppClient");
     //   request.setConfig(ConnectionManager.getRequestConfig());
        httpClient.executeMethod(postMethod);
        String strResponse = postMethod.getResponseBodyAsString();
    //    String respData = EntityUtils.toString(response.getEntity(), "UTF-8");
        WriteBankLogLn("发送消息收到的返回："+strResponse);
        return strResponse;
    }*/

    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                    + session.getPeerHost());
            return true;
        }
    };

    private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
                .getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
                .getSocketFactory());
    }

    static class miTM implements javax.net.ssl.TrustManager,
            javax.net.ssl.X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }

    public static CloseableHttpClient getHttpsClient() {
        CloseableHttpClient httpClient = null;
        SSLContext context;
        try {
            context = SSLContext.getInstance("SSL");
            context.init(null, new TrustManager[] {new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                        throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                        throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

            }}, new SecureRandom());

            HostnameVerifier verifier = new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(context, verifier);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpClient;
    }
}
